package com.wwc.common.controller;

import com.wwc.common.exception.BusinessException;
import com.wwc.common.response.CommonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理、数据预处理等
 */
@ControllerAdvice
public class ControllerExceptionHandler{
	private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class);

	/**
	 * 所有异常统一处理
	 */
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public CommonResponse<Object> exceptionHandler(Exception e){
		LOG.error("系统异常：", e);
		return new CommonResponse<>(false, "系统出现异常，请联系管理员", null);
	}

	/**
	 * 业务异常统一处理
	 */
	@ExceptionHandler(value = BusinessException.class)
	@ResponseBody
	public CommonResponse<Object> exceptionHandler(BusinessException e){
		LOG.error("业务异常：{}", e.getE().getDesc());
		return new CommonResponse<>(false, e.getE().getDesc(), null);
	}

	/**
	 * 校验异常统一处理
	 */
	@ExceptionHandler(value = BindException.class)
	@ResponseBody
	public CommonResponse<Object> exceptionHandler(BindException e){
		LOG.error("校验异常：{}", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
		return new CommonResponse<>(false, e.getBindingResult().getAllErrors().get(0).getDefaultMessage(), null);
	}
}
